from django.http import HttpResponseRedirect
from django.utils.translation import ugettext
from openid.consumer import consumer


class OpenidError(Exception):
    pass


def standartize_openid_url(s):
    s = s.lower()
#    if 'livejournal.com' in s:
#        s = s.rstrip('/')
#        if '/users/' in s:
#            s = 'http://%s.livejournal.com' % s.rsplit('/', 1)[-1]
    return s

def openid_auth_request(request, openid_url, next=None):
    oidconsumer = consumer.Consumer(request.session, None)
    immediate = False
    try:
        auth_request = oidconsumer.begin(openid_url)
    except consumer.DiscoveryFailure, exc:
        msg = ugettext('Error in discovery: %s') % exc[0]
        raise OpenidError(msg)

    if auth_request is None:
        msg = ugettext('No OpenID services found for %s') % openid_url
        raise OpenidError(msg)

    realm = 'http://' + request.get_host()
    if next:
        return_to = next
    else:
        return_to = realm + request.path

    redirect_url = auth_request.redirectURL(realm, return_to, immediate=immediate)
    return HttpResponseRedirect(redirect_url)


def openid_auth_handle_response(request, next=None):
    oidconsumer = consumer.Consumer(request.session, None)
    if next is None:
        #next = request.build_absolute_uri()
        next = 'http://' + request.get_host() + request.path
    return oidconsumer.complete(request.GET, next)

